﻿using Dt261.db;
using Dt261.help;
using Dt261.jsonmodel;
using Dt261.Model;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Panuon.UI.Silver;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Dt261.ViewModel
{
    class LoginWindowViewModel: ViewModelBase
    {
  

        #region 用户名/密码

        private string _Report;
        private string userName = string.Empty;
        private string passWord = string.Empty;

        private string userName2 = string.Empty;
        private string passWord2 = string.Empty;
        private bool _IsCancel = true;
        private bool _UserChecked;

        private string psdplaceholder;
        private int selectUserIndex;

        UserDb userDb;

        public LoginWindowViewModel()
        {
            userDb = new UserDb(dbconfig.DatabasePath);
            ReadConfigInfo();

            Psdplaceholder = "请输入密码";
        }

        private int jiami(int yuanlai)
        {
            return yuanlai ^ 912;
        }


        public int SelectUserIndex { get => selectUserIndex; set
            {
                selectUserIndex = value;
                RaisePropertyChanged();

                if(selectUserIndex == 1)
                {
                    Password = "";
                    string ma = "" + (new Random().Next(10000, 99999));

                  

                    var user = userDb.GetOneUserByName("超级用户");
                    int mima = Int32.Parse(ma);
                    user.Password =""+ jiami(mima);

                    userDb.UpdateUser(user);

                    Psdplaceholder = "请电话联系听力宝，验证码"+ma;
#if DEBUG
                    this.Report = "方便测试的"+user.Password;
#endif
                }
                else
                {
                    Psdplaceholder = "请输入密码";
                }
            }
        }



        public string Psdplaceholder { get => psdplaceholder; set { psdplaceholder = value; RaisePropertyChanged(); } }
        /// <summary>
        /// 数据库访问类型
        /// </summary>
        public string ServerType { get; set; }

        /// <summary>
        /// 皮肤样式
        /// </summary>
        public string SkinName { get; set; }

        /// <summary>
        /// 进度报告
        /// </summary>
        public string Report
        {
            get { return _Report; }
            set { _Report = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get { return userName; }
            set { userName = value; RaisePropertyChanged(); }
        }
        public string UserName2
        {
            get { return userName2; }
            set { userName2 = value; RaisePropertyChanged(); }
        }
        /// <summary>
        /// 记住密码
        /// </summary>
        public bool UserChecked
        {
            get { return _UserChecked; }
            set { _UserChecked = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password
        {
            get { return passWord; }
            set { passWord = value; RaisePropertyChanged(); }
        }
        public string Password2
        {
            get { return passWord2; }
            set { passWord2 = value; RaisePropertyChanged(); }
        }
        /// <summary>
        /// 禁用按钮
        /// </summary>
        public bool IsCancel
        {
            get { return _IsCancel; }
            set { _IsCancel = value; RaisePropertyChanged(); }
        }

        #endregion

        #region 命令(Binding Command)

        private RelayCommand _signCommand;

        public RelayCommand SignCommand
        {
            get
            {
                if (_signCommand == null)
                {
                    _signCommand = new RelayCommand(() => Login());
                }
                return _signCommand;
            }
        }


        private RelayCommand _netsignCommand;

        public RelayCommand NetSignCommand
        {
            get
            {
                if (_netsignCommand == null)
                {
                    _netsignCommand = new RelayCommand(() => NetLogin());
                }
                return _netsignCommand;
            }
        }
        private RelayCommand _exitCommand;

        public RelayCommand ExitCommand
        {
            get
            {
                if (_exitCommand == null)
                {
                    _exitCommand = new RelayCommand(() => ApplicationShutdown());
                }
                return _exitCommand;
            }
        }

        private ObservableCollection<string> userSource = null;

        public ObservableCollection<string> UserSource
        {
            get
            {
                if (this.userSource == null)
                {
                    this.userSource = new ObservableCollection<string>() { 
                       // new MaskingType() { Index = 0, Code = "00", Name = "白噪音" },
                       

                 };
                    this.userSource.Add("1");
                    this.userSource.Add("2");

                }
                return this.userSource;
            }
            set
            {
                this.userSource = value;
                RaisePropertyChanged();
            }
        }


        #endregion

        #region Login/Exit
        public bool IsMobilePhone(string input)
        {

            Regex regex = new Regex("^1[34578]\\d{9}$");
            return regex.IsMatch(input);

        }
        public async void NetLogin()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(UserName2)) 
                {
                    this.Report = "请输入手机号码";
                    return;
                }
                else if (!IsMobilePhone(UserName2))
                {
                    this.Report = "请输入正确的电话号码";
                    return;
                }
                else if (string.IsNullOrWhiteSpace(UserName2) || string.IsNullOrWhiteSpace(Password2))
                {
                    this.Report = "请输入用户名密码";
                    return;
                }


                #region login

                this.IsCancel = false;


                //handler = PendingBox.Show("正在查找蓝牙设备...", "请稍后", true, Application.Current.MainWindow, new PendingBoxConfigurations()
                //{
                //    LoadingForeground = "#5DBBEC".ToColor().ToBrush(),
                //    ButtonBrush = "#5DBBEC".ToColor().ToBrush(),

                //});
                //handler.Cancel += delegate
                //{

                //    handler.Close();
                //};


                this.Report = "正在验证登录 . . .";

                // Password = "qwerty";
                string psd = LoginWindowViewModel.Encrypt(Password2, "Douting_Tinglibao_0912");

                var http = Http.SharedHttp();
                //http.Request.Accept = HttpContentTypes.ApplicationJson;
                //http.Request.ContentType = HttpContentTypes.ApplicationXWwwFormUrlEncoded;

                var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("phone", UserName2),
                new KeyValuePair<string, string>("password", psd),
            });


                string result = http.GetResponse(content, Http.HOST + "tlyht/user/LoginDecrypt", "post");




                //var response = http.Post(, dict, HttpContentTypes.ApplicationXWwwFormUrlEncoded);
                Console.WriteLine(result);

                JObject o = (JObject)JsonConvert.DeserializeObject(result);

                if (null == Http.errorWithJsonObject(o))
                {
                    UserInfo info = JsonConvert.DeserializeObject<UserInfo>(o["userInfo"].ToString());
                   // if (UserChecked) SaveLoginInfo();


                    {
                        UserDb db = new UserDb(dbconfig.DatabasePath);
                        User user = db.GetOneUserByUid(info.userId);
                        if (user == null)
                        {
                            user = new User();
                            user.Uid = info.id;
                            user.Name = UserName2;
                            //user.IsLogin = true;
                            user.Password = psd;
                            db.AddUser(user);
                        }



                        GlobalData.LoginUser = user;
                    }

                    GlobalData.LoginNetUser = info;
                    this.Report = "登陆成功";
                    DMSkin.Core.Broadcast.PushBroadcast("LoginOK", UserName2);
                    return;
                }
                else
                {
                    this.Report = Http.errorWithJsonObject(o) + ",请重试!";
                }

                // 



                //var LoginTask = user.LoginAsync(UserName, CEncoder.Encode(Password));
                //var timeouttask = Task.Delay(3000);
                //var completedTask = await Task.WhenAny(LoginTask, timeouttask);
                //if (completedTask == timeouttask)
                //{
                //    this.Report = "系统连接超时,请重试!";
                //}
                //else
                //{
                //    var task = await LoginTask;
                //    if (task.success)
                //    {
                //        if (task.user == null)
                //        {
                //            this.Report = task.message;
                //            return;
                //        }
                //        if (UserChecked) SaveLoginInfo();
                //        var req = task.user;
                //        #region 设置用户基础信息

                //        Loginer.LoginerUser.Account = req.Account;
                //        Loginer.LoginerUser.UserName = req.UserName;
                //        Loginer.LoginerUser.IsAdmin = req.FlagAdmin == "1" ? true : false;
                //        Loginer.LoginerUser.Email = req.Email;
                //        var result = await user.LoginUserAuthAsync(req.Account);
                //        if (result.success && result.authorityEntity != null)
                //        {
                //            Loginer.LoginerUser.authorityEntity = result.authorityEntity;
                //        }

                //        this.Report = "加载用户信息 . . .";

                //        var dialog = ServiceProvider.Instance.Get<IModelDialog>("MainViewDlg");
                //        dialog.BindDefaultViewModel();
                //        Messenger.Default.Send(string.Empty, "ApplicationHiding");
                //        bool taskResult = await dialog.ShowDialog();
                //        this.ApplicationShutdown();

                //        #endregion
                //    }
                //    else
                //        this.Report = task.message;
                //}

                #endregion
            }
            catch (Exception ex)
            {
                this.Report = "连接超时，请确认网络连接正常";
            }
            finally
            {
                this.IsCancel = true;
            }
        }

        /// <summary>
        /// 登陆系统
        /// </summary>
        public async void Login()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password))
                {
                    this.Report = "请输入用户名密码";
                    return;
                }

     
                #region login

                this.IsCancel = false;
                var user = userDb.GetOneUserByName(UserName);
                if(user == null)
                {
                    this.Report = "用户名错误,请重试!";
                    return;
                }
                this.Report = "正在验证登录 . . .";

                if(user.Password != Password)
                {
                    this.Report = "密码错误,请重试!";
                }
                else
                {
                    if (UserChecked) SaveLoginInfo();
                    GlobalData.LoginUser = user;
                    DMSkin.Core.Broadcast.PushBroadcast("LoginOK", UserName);
                }
                //var LoginTask = user.LoginAsync(UserName, CEncoder.Encode(Password));
                //var timeouttask = Task.Delay(3000);
                //var completedTask = await Task.WhenAny(LoginTask, timeouttask);
                //if (completedTask == timeouttask)
                //{
                //    this.Report = "系统连接超时,请重试!";
                //}
                //else
                //{
                //    var task = await LoginTask;
                //    if (task.success)
                //    {
                //        if (task.user == null)
                //        {
                //            this.Report = task.message;
                //            return;
                //        }
                //        if (UserChecked) SaveLoginInfo();
                //        var req = task.user;
                //        #region 设置用户基础信息

                //        Loginer.LoginerUser.Account = req.Account;
                //        Loginer.LoginerUser.UserName = req.UserName;
                //        Loginer.LoginerUser.IsAdmin = req.FlagAdmin == "1" ? true : false;
                //        Loginer.LoginerUser.Email = req.Email;
                //        var result = await user.LoginUserAuthAsync(req.Account);
                //        if (result.success && result.authorityEntity != null)
                //        {
                //            Loginer.LoginerUser.authorityEntity = result.authorityEntity;
                //        }

                //        this.Report = "加载用户信息 . . .";

                //        var dialog = ServiceProvider.Instance.Get<IModelDialog>("MainViewDlg");
                //        dialog.BindDefaultViewModel();
                //        Messenger.Default.Send(string.Empty, "ApplicationHiding");
                //        bool taskResult = await dialog.ShowDialog();
                //        this.ApplicationShutdown();

                //        #endregion
                //    }
                //    else
                //        this.Report = task.message;
                //}

                #endregion
            }
            catch (Exception ex)
            {
                this.Report = ex.Message;
            }
            finally
            {
                this.IsCancel = true;
            }
        }

        /// <summary>
        /// 关闭系统
        /// </summary>
        public void ApplicationShutdown()
        {
           // Messenger.Default.Send("", "ApplicationShutdown");
           
        }

        #endregion

        #region 记住密码

        private static string Encrypt(string encryptStr, string key)
        {

            byte[] keyArray = new byte[32];
            UTF8Encoding.UTF8.GetBytes(key).CopyTo(keyArray, 0);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(encryptStr);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="decryptStr">密文</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        private static string Decrypt(string decryptStr, string key)
        {
            //byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] keyArray = new byte[32];
            UTF8Encoding.UTF8.GetBytes(key).CopyTo(keyArray, 0);
            byte[] toEncryptArray = Convert.FromBase64String(decryptStr);//Encoding.UTF8.GetBytes(decryptStr);// 
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return UTF8Encoding.UTF8.GetString(resultArray);
        }

        /// <summary>
        /// 读取本地配置信息
        /// </summary>
        public void ReadConfigInfo()
        {
            var basePath = Environment.CurrentDirectory;

            string cfgINI = System.IO.Path.Combine(basePath, "user.ini");
   
            try
            {
                if (File.Exists(cfgINI))
                {
                    IniFile ini = new IniFile(cfgINI);
                    UserName = ini.IniReadValue("Login", "User");
                    //  Password = ini.IniReadValue("Login", "Password");
                    UserChecked = ini.IniReadValue("Login", "SaveInfo") == "Y";

                    string psd  = ini.IniReadValue("Login", "Password");

                    if (psd != null)
                        Password =
                            Decrypt(psd, "Douting_Tinglibao_0912");
                    //else
                    //    Password = "";



                    //  SkinName = ini.IniReadValue("Skin", "Skin");
                    // ServerType = ini.IniReadValue("Server", "Bridge");
                }
            }
            catch
            {
                Report = "需重新输入密码";
            }

        }

        /// <summary>
        /// 保存登录信息
        /// </summary>
        private void SaveLoginInfo()
        {
            var basePath = Environment.CurrentDirectory;
           
            string cfgINI = System.IO.Path.Combine(basePath, "user.ini");
            IniFile ini = new IniFile(cfgINI);
            ini.IniWriteValue("Login", "User", UserName);

            string psd = Encrypt(Password, "Douting_Tinglibao_0912");
            ini.IniWriteValue("Login", "Password", psd);
            ini.IniWriteValue("Login", "SaveInfo", UserChecked ? "Y" : "N");
        }

        #endregion
    }
}

